package org.leon.dubbo.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.Timer;

@Activate(group = {CommonConstants.CONSUMER})
public class MonitorFilter implements Filter {

    private MonitorJob monitorJob;

    public MonitorFilter() {
        monitorJob = new MonitorJob();
        Timer timer = new Timer();
        timer.schedule(monitorJob, 5000, 5000);
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String methodName = invocation.getMethodName();
        long start = System.currentTimeMillis();
        try{
            return invoker.invoke(invocation);
        }finally {
            long end = System.currentTimeMillis();
            monitorJob.reportResponseTime(methodName, end-start);
        }
    }
}
